package com.handu.luna.boss.controller;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Base64;

import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.handu.luna.core.domain.goods.Goods;
import com.handu.luna.core.domain.promotion.PostForFreeActivity;
import com.handu.luna.core.domain.promotion.PostForFreeActivity.PostForFreeType;
import com.handu.luna.core.domain.search.GoodsSearchCondition;
import com.handu.luna.core.domain.search.PostForFreeActivitySearch;

@Controller
@RequestMapping("/promotion/postforfreeactivity/*")
public class PostForFreeActivityController extends BaseController{
	
	//点击搜索按钮
	@RequestMapping(value ="index",method = RequestMethod.POST)  //size = DEFAULT_PAGE_SIZE
	public BossModel index(PostForFreeActivitySearch postForFreeActivitySearch ,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort="id",direction= Direction.DESC) Pageable pageable)throws UnsupportedEncodingException{
    
		    return createModel("/promotion/postforfreeactivity/index")
				
				.add("postForFreeActivitySearch",postForFreeActivitySearch)
				.add("activityListsPage",new PostForFreeActivity().findAll(postForFreeActivitySearch,pageable))
				.add("viewState", Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(postForFreeActivitySearch).toString().getBytes("UTF-8")));
	}
	
	  
	//搜索 和列表 分页
	
	@RequestMapping(value = "index")
	public BossModel index(String viewState,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE,sort="id",direction= Direction.DESC) Pageable pageable)throws UnsupportedEncodingException {
		PostForFreeActivitySearch postForFreeActivitySearch;
		if(viewState != null && !viewState.trim().equals("")){ 
		   //解析传递过来的查询json字符串
			postForFreeActivitySearch = (PostForFreeActivitySearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getUrlDecoder().decode(viewState),"UTF-8")), PostForFreeActivitySearch.class);
 
		    return createModel("/promotion/postforfreeactivity/index")
				.add("activityListsPage",new PostForFreeActivity().findAll(postForFreeActivitySearch, pageable))				
				.add("postForFreeActivitySearch",postForFreeActivitySearch)
				.add("viewState", viewState);
	   }else{
		   postForFreeActivitySearch = new PostForFreeActivitySearch(); 
		    return createModel("/promotion/postforfreeactivity/index")
				.add("activityListsPage",new PostForFreeActivity().findAll(postForFreeActivitySearch, pageable))				
				.add("postForFreeActivitySearch",postForFreeActivitySearch)
				.add("viewState", "");
	   }
	}
	
	@RequestMapping(value = "add")
	public BossModel add(){     
		PostForFreeActivity postForFreeActivity = new PostForFreeActivity();
		postForFreeActivity.setPostForFreeType(PostForFreeType.ORDER);
		
	    GoodsSearchCondition searchCondition = new GoodsSearchCondition(GoodsSearchCondition.SearchType.POSTFORFREEACTIVITY);
		return createModel("promotion/postforfreeactivity/save")
				
				.add("PostForFreeActivityInfo", postForFreeActivity)
				.add("searchCondition",searchCondition)
				.add("selectableGoods", context.getGoodsRepository().findAll(searchCondition.searchabledGoods(searchCondition)))
                .add("brands", context.getBrandRepository().findAll())   //搜索所有的品牌  ，当做搜索条件的，相当于单选按钮
                .add("categorys", context.getCategoryRepository().findAll())  //搜索所有的商品分类
		        .add("brandList", context.getBrandRepository().findAll());  //当做checkbox,可以多选;
	}
	     
	
	@RequestMapping(value = "edit/{id}")
	public BossModel edit(@PathVariable long id) {
		PostForFreeActivity list = context.getPostForFreeActivityRepository().findOne(id);
		GoodsSearchCondition searchCondition = new GoodsSearchCondition(id,GoodsSearchCondition.SearchType.POSTFORFREEACTIVITY);
		
		if(list.getPostForFreeType()==PostForFreeType.SINGLEGOOD){
			if(list.getGoodsIdArr()!=null && list.getGoodsIdArr()!=""){	 
			      return createModel("promotion/postforfreeactivity/save")
			    		    .add("searchCondition",searchCondition)
							.add("PostForFreeActivityInfo",list)
							.add("hidden_divOrderPrice", PostForFreeType.SINGLEGOOD)
							.add("selectableGoods", context.getGoodsRepository().findAll(searchCondition.searchabledGoods(searchCondition)))
                            .add("brands", context.getBrandRepository().findAll())    //当做搜索条件的，相当于单选按钮
                            .add("categorys", context.getCategoryRepository().findAll())
                            .add("brandList", context.getBrandRepository().findAll());  //当做checkbox,可以多选;
			}else{
				return createModel("promotion/postforfreeactivity/save")
						.add("searchCondition",searchCondition)
						.add("PostForFreeActivityInfo",list)
						.add("hidden_divOrderPrice", PostForFreeType.SINGLEGOOD)
						.add("brands", context.getBrandRepository().findAll())    //当做搜索条件的，相当于单选按钮
                        .add("categorys", context.getCategoryRepository().findAll())
                        .add("brandList", context.getBrandRepository().findAll());  //当做checkbox,可以多选;
			}

		}else if(list.getPostForFreeType()==PostForFreeType.BRAND){
			return createModel("promotion/postforfreeactivity/save")
					.add("searchCondition",searchCondition)
					.add("PostForFreeActivityInfo",list)
					.add("hidden_divOrderPrice", PostForFreeType.BRAND)
					.add("brands", context.getBrandRepository().findAll())   //当做搜索条件的，相当于单选按钮
                    .add("categorys", context.getCategoryRepository().findAll())
                    .add("brandList", context.getBrandRepository().findAll());  //当做checkbox,可以多选;
			
		}else{
			
			return createModel("promotion/postforfreeactivity/save")
					.add("searchCondition",searchCondition)
					.add("PostForFreeActivityInfo",list)
					.add("brands", context.getBrandRepository().findAll())  //当做搜索条件的，相当于单选按钮
                    .add("categorys", context.getCategoryRepository().findAll())
                    .add("brandList", context.getBrandRepository().findAll());  //当做checkbox,可以多选
		}	  		
	}
	
	@RequestMapping(value = "delete")
	public BossModel delete(
			String viewState,
			long id,
			@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE,sort="id",direction= Direction.DESC) Pageable pageable,RedirectAttributes redirectAttributes) {
		
		//PostForFreeActivity list = context.getPostForFreeActivityRepository().findOne(id);
		//if(list.getPostForFreeType() == PostForFreeType.SINGLEGOOD && StringUtils.isNotBlank(list.getGoodsIdArr())){   
		//	throw new BossException("该包邮活动下存在商品，不能移除！"); 
			
		//}else{
			context.getPostForFreeActivityRepository().delete(id);
		//}
		return createModel("promotion/postforfreeactivity/activity_table")
				.add("activityListsPage",context.getPostForFreeActivityRepository().findAll(pageable))
				.add("viewState", viewState);
	}
	
	
	@RequestMapping(value="save", method = RequestMethod.POST)
	@InitBinder(value={"postForFreeName","goodsIdArr","brands","postForFreeType","orderPrice","startDate","endDate","postForFreeInstruction"})//,"categoryId" ,"brandId" ,"goodSn" ,"keyword","goodsIdArr"
	public BossModel save(@Valid @ModelAttribute("postForFreeActivity") final PostForFreeActivity postForFreeActivity,final BindingResult bindingResult,RedirectAttributes redirectAttributes){
	//public BossModel save(String viewState,@Valid @ModelAttribute("sp") final SalesPromotion sp,final BindingResult bindingResult, RedirectAttributes redirectAttributes, @PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException{
		String message = "";
		if(bindingResult.hasErrors()){
			return createModel("promotion/postforfreeactivity/save")
					 .add("PostForFreeActivityInfo",postForFreeActivity)
	                 .add("selectableGoods", context.getGoodsRepository().findAll(new Goods().searchSelectAble(Goods.SearchType.COMBOSEARCH, 0, null, null, null, null)))
	                 .add("brands", context.getBrandRepository().findAll())
	                 .add("categorys", context.getCategoryRepository().findAll());
		}
		
		if(postForFreeActivity.getPostForFreeType() == PostForFreeType.SINGLEGOOD){
			postForFreeActivity.setOrderPrice(null);
			postForFreeActivity.setBrands(null);
			postForFreeActivity.setBrandsIdList(null);
		}else if(postForFreeActivity.getPostForFreeType() == PostForFreeType.ORDER){
			postForFreeActivity.setGoodsIdArr(null);
			postForFreeActivity.setBrands(null);
			postForFreeActivity.setBrandsIdList(null);
		}else if(postForFreeActivity.getPostForFreeType() == PostForFreeType.BRAND){
			postForFreeActivity.setOrderPrice(null);
			postForFreeActivity.setGoodsIdArr(null);
		}


		
	  //判断传过来的 包邮名称 是否全部为空格
	  String name = postForFreeActivity.getPostForFreeName().trim();
	  
  if(postForFreeActivity.getPostForFreeType() == PostForFreeType.ORDER){
	  int orderprice = postForFreeActivity.getOrderPrice().compareTo(BigDecimal.ZERO); //和0，Zero比较
	    if(name.isEmpty()){
			message = "包邮名称不能为空！";
			
		}else if(postForFreeActivity.getPostForFreeType()==null){
			message = "包邮类型不能为空！";
			
		}else if(postForFreeActivity.getOrderPrice() ==null){
			message = "订单金额不能为空!";
			
		}else if(postForFreeActivity.getStartDate()==null){
			message = "开始时间不能为空!";
			
		}else if(postForFreeActivity.getEndDate()==null){
			message = "结束时间不能为空!";   
			
		}else if(orderprice<=0){
			message = "订单金额不正确！";
			
		}else if((null==postForFreeActivity.getId() || postForFreeActivity.getId()==0) && (!name.isEmpty()) && postForFreeActivity.getPostForFreeType()!=null && postForFreeActivity.getOrderPrice()!=null && postForFreeActivity.getStartDate()!=null && postForFreeActivity.getEndDate()!=null)
		{	
			context.getPostForFreeActivityRepository().save(postForFreeActivity);
			message = "添加" + postForFreeActivity.getPostForFreeName() +"成功";
		}else if((null!=postForFreeActivity.getId() || postForFreeActivity.getId()!=0) && (!name.isEmpty()) && postForFreeActivity.getPostForFreeType()!=null && postForFreeActivity.getOrderPrice()!=null && postForFreeActivity.getStartDate()!=null && postForFreeActivity.getEndDate()!=null){
			//postForFreeActivity.update();
			context.getPostForFreeActivityRepository().save(postForFreeActivity);
			message = "修改" + postForFreeActivity.getPostForFreeName() +"成功";
		}
		
		//redirectAttributes.addFlashAttribute("message",message);
		//return createModel("redirect:index");		
		
	}else if(postForFreeActivity.getPostForFreeType() == PostForFreeType.SINGLEGOOD){
	        if(name.isEmpty()){
				message = "包邮名称不能为空！";
				
			}else if(postForFreeActivity.getPostForFreeType()==null){
				message = "包邮类型不能为空！";
				
			}else if(postForFreeActivity.getStartDate()==null){
				message = "开始时间不能为空!";
				
			}else if(postForFreeActivity.getEndDate()==null){
				message = "结束时间不能为空!";
				
			}else if(postForFreeActivity.getGoodsIdArr()==null){
				message = "您还没有添加单品！";
			}else if((null==postForFreeActivity.getId() || postForFreeActivity.getId()==0) && (!name.isEmpty()) && postForFreeActivity.getPostForFreeType()!=null && postForFreeActivity.getStartDate()!=null && postForFreeActivity.getEndDate()!=null && postForFreeActivity.getGoodsIdArr()!=null)
			{
				context.getPostForFreeActivityRepository().save(postForFreeActivity);
				message = "添加" + postForFreeActivity.getPostForFreeName() +"成功";
			}else if((null!=postForFreeActivity.getId() || postForFreeActivity.getId()!=0) && (!name.isEmpty()) && postForFreeActivity.getPostForFreeType()!=null && postForFreeActivity.getStartDate()!=null && postForFreeActivity.getEndDate()!=null && postForFreeActivity.getGoodsIdArr()!=null){
				//postForFreeActivity.update();
				context.getPostForFreeActivityRepository().save(postForFreeActivity);
				message = "修改" + postForFreeActivity.getPostForFreeName() +"成功";
			}
	}else if(postForFreeActivity.getPostForFreeType() == PostForFreeType.BRAND){
        if(name.isEmpty()){
			message = "包邮名称不能为空！";
			
		}else if(postForFreeActivity.getPostForFreeType()==null){
			message = "包邮类型不能为空！";
			
		}else if(postForFreeActivity.getStartDate()==null){
			message = "开始时间不能为空!";
			
		}else if(postForFreeActivity.getEndDate()==null){
			message = "结束时间不能为空!";
			
		}else if(postForFreeActivity.getBrandsIdList()==null){
			message = "请选择商品品牌！";
		}else if((null==postForFreeActivity.getId() || postForFreeActivity.getId()==0) && (!name.isEmpty()) && postForFreeActivity.getPostForFreeType()!=null && postForFreeActivity.getStartDate()!=null && postForFreeActivity.getEndDate()!=null && postForFreeActivity.getBrandsIdList()!=null)
		{
			context.getPostForFreeActivityRepository().save(postForFreeActivity);
			message = "添加" + postForFreeActivity.getPostForFreeName() +"成功";
		}else if((null!=postForFreeActivity.getId() || postForFreeActivity.getId()!=0) && (!name.isEmpty()) && postForFreeActivity.getPostForFreeType()!=null && postForFreeActivity.getStartDate()!=null && postForFreeActivity.getEndDate()!=null && postForFreeActivity.getBrandsIdList()!=null){
			postForFreeActivity.update();
			//context.getPostForFreeActivityRepository().save(postForFreeActivity);
			message = "修改" + postForFreeActivity.getPostForFreeName() +"成功";
		}
     }
			
			redirectAttributes.addFlashAttribute("message",message);
			return createModel("redirect:index");	
	}
}
		


